/**
 * 
 */
package wpmp.security.mgr.base;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 3:56:17 PM Jan 4, 2013
 */
public class SqlUtils {

	public static final String DEFAULT_ALIAS = "thiz";

	public static String getOrderBySql(String sort, String dir) {
		return getOrderBySql(sort, dir, DEFAULT_ALIAS);
	}

	public static String getOrderBySql(String sort, String dir, String alias) {
		alias = StringUtils.stripToEmpty(alias);
		StringBuilder orderBySql = new StringBuilder();
		int index = sort.indexOf(".");
		if (index == -1) {
			if (StringUtils.isNotBlank(alias)) {
				orderBySql.append(alias).append(".");
			}
			orderBySql.append(toColumnName(sort));
		}
		else {
			orderBySql.append(sort.substring(0, index + 1));
			orderBySql.append(toColumnName(sort.substring(index + 1)));
		}
		orderBySql.append(' ').append(dir);
		return orderBySql.toString();
	}

	public static String getOrderBySql(SqlOrder... sqlOrders) {
		return getOrderBySql(DEFAULT_ALIAS, sqlOrders);
	}

	public static String getOrderBySql(String alias, SqlOrder... sqlOrders) {
		if (ArrayUtils.isEmpty(sqlOrders)) {
			return StringUtils.EMPTY;
		}
		alias = StringUtils.stripToEmpty(alias);
		StringBuilder orderBySql = new StringBuilder();
		for (SqlOrder sqlOrder : sqlOrders) {
			orderBySql.append(',');
			if (!sqlOrder.getPropertyName().contains(".")) {
				orderBySql.append(alias).append(".");
			}
			orderBySql.append(sqlOrder.toString());
		}
		return orderBySql.deleteCharAt(0).toString();
	}

	/**
	 * 数据库的字段名称转换成pojo对象的属性名称
	 * 
	 * @param columnName
	 * @return
	 */
	public static String toPropertyName(String columnName) {
		StringBuffer sb = new StringBuffer();
		boolean flag = false;
		for (int i = 0; i < columnName.length(); i++) {
			char ch = columnName.charAt(i);
			if (ch == '_') {
				flag = true;
			}
			else {
				if (flag) {
					sb.append(Character.toUpperCase(ch));
					flag = false;
				}
				else {
					sb.append(Character.toLowerCase(ch));
				}
			}
		}
		return sb.toString();
	}

	/**
	 * pojo对象的属性名称转换成数据库的字段名称
	 * 
	 * @param propertyName
	 * @return
	 */
	public static String toColumnName(String propertyName) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < propertyName.length(); i++) {
			char ch = propertyName.charAt(i);
			if (Character.isUpperCase(ch)) {
				sb.append("_");
				sb.append(ch);
			}
			else {
				sb.append(ch);
			}
		}
		return sb.toString().toLowerCase();
	}
}
